<template>
    <nav-bar />
    <view class="goods-list-page">
        <!-- 左侧分类栏 -->
        <scroll-view class="sidebar" scroll-y>
            <!-- 分类列表循环 -->
            <view v-for="(cat, idx) in categories" :key="cat.id" class="category"
                :class="{ active: cat.id === activeCategoryIdx }" @click="onCategoryClick(cat)">
                {{ cat.name }}
            </view>
            <!-- 查看二级分类按钮 -->
            <button class="manage-btn" @click="onViewSubCategory">查看二级分类</button>
        </scroll-view>

        <!-- 右侧内容区 -->
        <view class="main-content">
            <view class="header">
                <!-- 搜索框 -->
                <view class="search-box">
                    <input 
                        class="search-input" 
                        type="text" 
                        v-model="searchKeyword"
                        placeholder="搜索商品名称或编号"
                        @confirm="onSearch"
                    />
                </view>
                <!-- 搜索按钮 -->
                <button class="search-btn" @click="onSearch">搜索</button>
            </view>
            <!-- 商品总数 -->
            <view class="goods-count">商品数：{{ goodsList.length }}</view>
            <scroll-view class="goods-scroll" scroll-y refresher-enabled :refresher-triggered="isRefreshing" @refresherrefresh="onRefresh">
                <view class="goods-list">
                    <!-- 商品项循环 -->
                    <view @click="onGoodsItemClick(item)" class="goods-item" v-for="(item, idx) in goodsList" :key="idx">
                        <!-- 商品图片 -->
                        <image class="goods-img" 
                            :src="item.image && item.image.length > 0 ? IntranetConfig.domain + item.image[0].image : ''" 
                            mode="aspectFill"
                            v-if="item.image && item.image.length > 0" 
                        />
                        <!-- 图片骨架屏 -->
                        <view class="img-skeleton" v-else></view>
                        <!-- 商品信息 -->
                        <view class="goods-info">
                            <!-- 商品名称 -->
                            <view class="goods-title" :title="item.name || '商品名称'">
                                {{ item.name || '商品名称' }}
                            </view>
                            <!-- 售价和库存 -->
                            <view class="goods-meta">
                                <view class="price-row">
                                    <text class="price-label">售价：</text>
                                    <text class="price">{{ item.price }}元</text>
                                </view>
                                <view class="stock-row">
                                    <text class="stock-label">库存：</text>
                                    <text class="stock">{{ item.stock }}个</text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </scroll-view>
        </view>

        <!-- 二级分类弹窗 -->
        <view v-if="showSubCategoryPopup" class="sub-category-popup-mask" @click.self="showSubCategoryPopup = false">
            <view class="sub-category-popup">
                <view class="popup-header">
                    <text class="popup-title">全部二级分类</text>
                    <text class="popup-close" @click="showSubCategoryPopup = false">×</text>
                </view>
                <view class="popup-content">
                    <view v-if="subCategoryList.length === 0" class="empty-tip">暂无二级分类</view>
                    <view v-else>
                        <view class="sub-category-item" v-for="item in subCategoryList" :key="item.id" @click="onSubCategoryClick(item)">
                            <view class="sub-category-name">{{ item.name }}</view>
                            <view class="sub-category-remark" @click.stop="onRemarkClick(item.remark)">
                                <text class="remark-ellipsis">{{ item.remark }}</text>
                                <text v-if="item.remark && item.remark.length > 20" class="remark-more">...查看</text>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <!-- 备注弹窗 -->
        <view v-if="showRemarkPopup" class="remark-popup-mask" @click.self="showRemarkPopup = false">
            <view class="remark-popup">
                <view class="popup-header">
                    <text class="popup-title">备注内容</text>
                    <text class="popup-close" @click="showRemarkPopup = false">×</text>
                </view>
                <view class="popup-content">
                    <view class="remark-full">{{ currentRemark }}</view>
                </view>
            </view>
        </view>
    </view>

    <my-tabbar />
    <add-goods-button />

</template>

<script setup>
import { ref, computed } from 'vue'
import MyTabbar from '@/components/my-tabbar.vue'
import AddGoodsButton from '@/components/add-goods-button/add-goods-button.vue'
import { IntranetConfig } from '@/static/js/config'
import { onLoad } from '@dcloudio/uni-app'
onLoad(() => {
    // 隐藏tabbar
    uni.hideTabBar()
})
// 分类列表
const categories = ref([])
const activeCategoryIdx = ref(0) // 当前激活的分类索引

// 商品数据（只存当前分类的）
const goodsList = ref([])

// 搜索相关
const searchKeyword = ref('')

// 分类点击事件
function onCategoryClick(idx) {
    console.log("分类点击", idx);
    // 检查分类状态
    if (idx.status !== 1) {
        uni.showToast({
            title: '该分类暂时不可用',
            icon: 'none'
        })
        return
    }

    activeCategoryIdx.value = idx.id
    // 请求商品数据
    getProductsByCategory(idx, idx.id)
}

// 请求分类数据
function getCategories() {
    let url = IntranetConfig.domain + 'api/category/get_category_list/'
    uni.request({
        url: url,
        method: 'GET',
        header: IntranetConfig.headers,
        success: (res) => {
            // 过滤出状态正常的分类
            const normalCategories = res.data.data.filter(cat => cat.status === 1)
            categories.value = [{
                "id": 0,
                "name": "全部商品",
                "status": 1,
                "remark": "全部商品",
                "create_time": "2025-05-05 15:54:46",
                "update_time": "2025-05-05 21:25:39"
            }, ...normalCategories]
            onCategoryClick(categories.value[0])
        },
        fail: (err) => {
            console.log(err)
        },
        complete: () => {
            console.log('请求完成')
        }
    })
}
getCategories()
// 请求商品数据
function getProductsByCategory(category, idx) {
    let url = IntranetConfig.domain + 'api/category/get_products_by_category/' + idx + '/'
    uni.request({
        url: url,
        method: 'GET',
        header: IntranetConfig.headers,
        success: (res) => {
            let data = res.data.data;
            // 过滤出状态正常的商品
            data = data.filter(item => item.status === 1).map((item) => {
                if (item.category) {
                    item.data_id = item.category;
                }
                if (item.category_sub) {
                    item.data_id = item.category_sub;
                }
                return item;
            })
            goodsList.value = data;
        },
        fail: (err) => {
            console.log(err)
        },
        complete: () => {
            console.log('请求完成')
        }
    })
}

// 商品项点击事件，跳转到编辑页面
function onGoodsItemClick(item) {
    console.log(item)
    uni.navigateTo({
        url: '/pages/goods_edit/goods_edit?id=' + item.id
    })
}

const showSubCategoryPopup = ref(false)
const subCategoryList = ref([])
const showRemarkPopup = ref(false)
const currentRemark = ref('')

function onViewSubCategory() {
    uni.showLoading({ title: '加载中', mask: true })
    uni.request({
        url: IntranetConfig.domain + 'api/category/get_category_sub_list/',
        method: 'GET',
        header: IntranetConfig.headers,
        success: (res) => {
            if (res.data.code === 200) {
                // 过滤出状态正常的二级分类
                subCategoryList.value = res.data.data.filter(cat => cat.status === 1)
                showSubCategoryPopup.value = true
            } else {
                uni.showToast({ title: res.data.msg || '获取失败', icon: 'error' })
            }
        },
        fail: () => {
            uni.showToast({ title: '网络错误', icon: 'error' })
        },
        complete: () => {
            uni.hideLoading()
        }
    })
}

function onRemarkClick(remark) {
    currentRemark.value = remark
    showRemarkPopup.value = true
}

function onSubCategoryClick(item) {
    // 检查二级分类状态
    if (item.status !== 1) {
        uni.showToast({
            title: '该分类暂时不可用',
            icon: 'none'
        })
        return
    }
    // 关闭二级分类弹窗
    showSubCategoryPopup.value = false
    // 获取该二级分类下的商品
    getProductsByCategory(item, item.id)
}

function getProductsBySubCategory(subCategoryId) {
    let url = IntranetConfig.domain + 'api/category/get_products_by_category_sub/' + subCategoryId + '/'
    uni.request({
        url: url,
        method: 'GET',
        header: IntranetConfig.headers,
        success: (res) => {
            let data = res.data.data || []
            goodsList.value = data
        },
        fail: (err) => {
            console.log(err)
        },
        complete: () => {
            console.log('请求完成')
        }
    })
}

const isRefreshing = ref(false)

function onRefresh() {
    isRefreshing.value = true
    // 重新请求当前分类商品
    let currentCat = categories.value.find(cat => cat.id === activeCategoryIdx.value)
    if (currentCat) {
        getProductsByCategory(currentCat, currentCat.id)
    }
    setTimeout(() => {
        isRefreshing.value = false
    }, 800)
}

// 搜索商品
function onSearch() {
    if (!searchKeyword.value.trim()) {
        // 如果搜索关键词为空，恢复显示当前分类的商品
        let currentCat = categories.value.find(cat => cat.id === activeCategoryIdx.value)
        if (currentCat) {
            getProductsByCategory(currentCat, currentCat.id)
        }
        return
    }

    uni.showLoading({ title: '搜索中...' })
    uni.request({
        url: IntranetConfig.domain + 'api/product/search_product/',
        method: 'GET',
        data: {
            name: searchKeyword.value.trim(),
        },
        header: IntranetConfig.headers,
        success: (res) => {
            if (res.data.code === 200) {
                // 过滤出状态正常的商品，并确保image属性存在
                goodsList.value = res.data.data.filter(item => item.status === 1).map(item => {
                    // 确保image属性是数组格式
                    const images = Array.isArray(item.images) ? item.images : [];
                    console.log('商品图片数据:', item.name, images); // 添加调试日志
                    return {
                        ...item,
                        image: images
                    };
                });
            } else {
                uni.showToast({
                    title: res.data.msg || '搜索失败',
                    icon: 'none'
                })
            }
        },
        fail: () => {
            uni.showToast({
                title: '网络错误',
                icon: 'none'
            })
        },
        complete: () => {
            uni.hideLoading()
        }
    })
}
</script>

<style scoped lang="scss">
.goods-list-page {
    display: flex;
    width: 100vw;
    height: 100vh;
    background: #fff;
    font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
    overflow: hidden;
}

.sidebar {
    width: 180rpx;
    min-width: 120px;
    background: #fafafa;
    border-right: 1px solid #f0f0f0;
    display: flex;
    flex-direction: column;
    padding-top: 20rpx;
    box-sizing: border-box;
    overflow-y: auto;
    height: 100vh;

    .category {
        padding: 18rpx 0 18rpx 24rpx;
        font-size: 28rpx;
        color: #333;
        cursor: pointer;
        transition: background 0.2s, color 0.2s;

        &.active {
            color: #ff7e2d;
            font-weight: bold;
            background: #fff;
            border-left: 4rpx solid #ff7e2d;
        }
    }

    .manage-btn {
        margin: 40rpx 10rpx 0 10rpx;
        padding: 12rpx 0;
        background: #fff;
        border: 1rpx solid #ccc;
        border-radius: 8rpx;
        color: #666;
        font-size: 24rpx;
        cursor: pointer;
    }
}

.main-content {
    flex: 1 1 0%;
    min-width: 0;
    display: flex;
    flex-direction: column;
    height: 100vh;
    padding: 0;
    box-sizing: border-box;
    overflow: hidden;

    .header {
        flex-shrink: 0;
        display: flex;
        padding: 20rpx;
        align-items: center;
        gap: 20rpx;
        margin-bottom: 12rpx;
        background: #fff;
        z-index: 10;
        box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);

        .search-box {
            flex: 1;
            max-width: 500rpx;
            position: relative;
            margin-right: 0;

            .search-input {
                width: 100%;
                height: 72rpx;
                background: #f5f5f5;
                border-radius: 36rpx;
                padding: 0 32rpx;
                font-size: 28rpx;
                color: #333;
                border: 2rpx solid #eee;
                transition: all 0.3s ease;

                &:focus {
                    border-color: #ff7e2d;
                    background: #fff;
                    box-shadow: 0 0 0 2rpx rgba(255,126,45,0.1);
                }
            }
        }

        .search-btn {
            height: 72rpx;
            padding: 0 32rpx;
            background: #ff7e2d;
            color: #fff;
            font-size: 28rpx;
            border-radius: 36rpx;
            border: none;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            white-space: nowrap;

            &:active {
                background: darken(#ff7e2d, 5%);
                transform: scale(0.98);
            }
        }
    }

    .goods-count {
        font-size: 24rpx;
        color: #999;
        padding: 0 20rpx 12rpx;
        background: #fff;
    }

    .goods-scroll {
        flex: 1 1 0%;
        min-width: 0;
        overflow-y: auto;
        overflow-x: hidden;
        padding: 0;
        padding-bottom: 100rpx;
    }
}

.goods-list {
    display: flex;
    flex-direction: column;
    gap: 18rpx;
    min-width: 340rpx;
    padding: 0 20rpx;

    .goods-item {
        display: flex;
        align-items: center;
        background: #fff;
        border-radius: 16rpx;
        box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);
        min-width: 320rpx;
        max-width: 100%;
        padding: 24rpx;
        transition: all 0.3s ease;

        &:active {
            transform: scale(0.99);
            box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);
        }

        .goods-img,
        .img-skeleton {
            width: 120rpx;
            height: 120rpx;
            min-width: 120rpx;
            min-height: 120rpx;
            margin-right: 24rpx;
            border-radius: 12rpx;
            background: #fafafa;
            object-fit: cover;
            border: 2rpx solid #f5f5f5;
        }

        .goods-info {
            flex: 1 1 0%;
            min-width: 0;
            display: flex;
            flex-direction: column;
            justify-content: center;

            .goods-title {
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                overflow: hidden;
                font-size: 32rpx;
                color: #222;
                font-weight: 500;
                margin-bottom: 12rpx;
                line-height: 1.4;
                max-width: 420rpx;
            }

            .goods-meta {
                display: flex;
                flex-direction: column;
                gap: 8rpx;
                font-size: 24rpx;

                .price-row, .stock-row {
                    display: flex;
                    align-items: center;
                }

                .price-label, .stock-label {
                    color: #666;
                    margin-right: 8rpx;
                }

                .price {
                    color: #ff7e2d;
                    font-weight: bold;
                }

                .stock {
                    color: #f7b26a;
                    background: rgba(247,178,106,0.1);
                    padding: 4rpx 12rpx;
                    border-radius: 20rpx;
                }
            }
        }
    }
}

// 二级分类弹窗样式
.sub-category-popup-mask {
    position: fixed;
    left: 0; top: 0; right: 0; bottom: 0;
    background: rgba(0,0,0,0.25);
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
}
.sub-category-popup {
    width: 600rpx;
    max-width: 90vw;
    background: #fff;
    border-radius: 18rpx;
    box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.12);
    overflow: hidden;
}
.popup-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx;
    border-bottom: 1rpx solid #f5f5f5;
    background: #fff;
    .popup-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
    }
    .popup-close {
        font-size: 40rpx;
        color: #999;
        padding: 16rpx;
        margin: -16rpx;
        border-radius: 50%;
        transition: all 0.3s;
        &:active { background: #f5f5f5; }
    }
}
.popup-content {
    padding: 32rpx;
    max-height: 600rpx;
    overflow-y: auto;
    .empty-tip {
        color: #bbb;
        text-align: center;
        font-size: 28rpx;
        padding: 60rpx 0;
    }
    .sub-category-item {
        padding: 18rpx 0;
        border-bottom: 1rpx solid #f5f5f5;
        cursor: pointer;
        .sub-category-name {
            font-size: 30rpx;
            color: #222;
            font-weight: 500;
        }
        .sub-category-remark {
            font-size: 24rpx;
            color: #999;
            margin-top: 6rpx;
            display: flex;
            align-items: center;
            .remark-ellipsis {
                max-width: 320rpx;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                display: inline-block;
            }
            .remark-more {
                color: #ff7e2d;
                margin-left: 8rpx;
                font-size: 22rpx;
                cursor: pointer;
            }
        }
    }
    .sub-category-item:last-child {
        border-bottom: none;
    }
}

// 备注弹窗样式
.remark-popup-mask {
    position: fixed;
    left: 0; top: 0; right: 0; bottom: 0;
    background: rgba(0,0,0,0.25);
    z-index: 1001;
    display: flex;
    align-items: center;
    justify-content: center;
}
.remark-popup {
    width: 600rpx;
    max-width: 90vw;
    background: #fff;
    border-radius: 18rpx;
    box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.12);
    overflow: hidden;
    .popup-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 32rpx;
        border-bottom: 1rpx solid #f5f5f5;
        background: #fff;
        .popup-title {
            font-size: 32rpx;
            font-weight: 600;
            color: #333;
        }
        .popup-close {
            font-size: 40rpx;
            color: #999;
            padding: 16rpx;
            margin: -16rpx;
            border-radius: 50%;
            transition: all 0.3s;
            &:active { background: #f5f5f5; }
        }
    }
    .popup-content {
        padding: 32rpx;
        .remark-full {
            font-size: 28rpx;
            color: #333;
            word-break: break-all;
        }
    }
}
</style>
